package com.miyake.loveviewweb.server.controller;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.upload.FileItem;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Key;
import com.miyake.loveviewweb.server.meta.UserModelMeta;
import com.miyake.loveviewweb.server.service.MyUserKey;
import com.miyake.loveviewweb.shared.model.BinaryModel;
import com.miyake.loveviewweb.shared.model.LvBlob;
import com.miyake.loveviewweb.shared.model.UserModel;

public class UserImageController extends Controller {

    @Override
    public Navigation run() throws Exception {
        if (isGet()) {
            Key key = Datastore.stringToKey(this.request.getParameter("key"));
            UserModel userModel = Datastore.get(UserModel.class, key);
            if (userModel.getImage() != null) {
                BinaryModel bin = Datastore.get(BinaryModel.class, userModel.getImage());
                this.response.setContentType(bin.getContentType());            
                this.response.getOutputStream().write(bin.getBlobData().getBytes());
                this.response.getOutputStream().flush();
                this.response.getOutputStream().close();
            }
        }
        else if (isPost()){
            UserModel userModel = Datastore.get(UserModel.class, MyUserKey.get());
            FileItem formFile = requestScope("fileupload");
            Key key = Datastore.allocateId(userModel.getKey(), BinaryModel.class);
            
            if (userModel.getImage() != null) {
                Datastore.delete(userModel.getImage());
            }
            
            BinaryModel binary = new BinaryModel();
            binary.setBlobData(new Blob(formFile.getData()));
            binary.setContentType(formFile.getContentType());
            binary.setKey(key);
            Datastore.put(binary);
            userModel.setImage(key);
            Datastore.put(userModel);
         
        }
        
        return null;//forward("userImage.jsp");
    }
}
